'use strict';

const _ = require('lodash')

//封装sequelize常用对象操作

// 过滤掉为空的对象
module.exports = exports = {}

//过滤空的查询对象
exports.filterEmptyQuery = function (obj) {
    if (!obj || _.isEmpty(obj)) return undefined
    let keys = Object.keys(obj)
    for (var key of keys) {
        if (_.isObject(obj[key]) && _.isEmpty(obj[key])) {
            delete obj[key]
        } else if (obj[key] === null || obj[key] === undefined || obj[key] === '') {
            delete obj[key]
        }
    }
}

//转换分页参数
exports.parsePageParam = function (obj) {
    let { where, attributes, order, offset, limit, page } = obj || {}

    //参数类型处理
    if (!limit) {
        limit = 10
    }
    if (!page) {
        page = 1
    }
    //计算offset
    offset = (page - 1) * limit
    //
    if (!order) {
        order = [
            ['created_at', 'desc']
        ]
    } else if (typeof order === 'string') {
        var arr = order.split(',')
        if (arr.length == 2) {
            order = arr
        } else {
            order = [
                [order, 'desc']
            ]
        }
    }

    Object.assign(obj, { order, offset, limit, offset })
}